# coding=utf-8


import sys

reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()

import web
import datetime
from components.logger import logger
from persistents import RedisServices
from components.task_monkey_test import TaskMonkeyTest, TaskTimingReport, TaskHandlerTerminated
from utils.ExcelUtils import DevicesManagerTask
from managers.globalarea import app_config
from utils.test import zip_task_files, crash_list, anr_list, analysis_crash_and_anr

urls = (
    '/monkey/(.*)', 'controllers.monkeycontroller.monkeycontroller',
    '/output/(.*)', 'controllers.downloadcontroller.downloadcontroller',
    '/task/(.*)', 'controllers.taskcontroller.TaskController',
    '/(.*)', 'controllers.defaultcontroller.defaultcontroller'
)

timing_tasks_config = {
    'monkey': TaskMonkeyTest,
    'report': TaskTimingReport,
    'terminate': TaskHandlerTerminated,
}


def clear_task():
    """
    清除之前的定时任务
    :return:
    """
    r = RedisServices()
    ex_keys_list = r.keys(app_config.expired_key_prefix + '*')
    ex_keys_list.extend(r.keys(app_config.report_expired_key_prefix + '*'))
    [r.delete(k) for k in ex_keys_list]
    # r.setex('report_' + str(datetime.datetime.now()), 5)


def launch():
    # zip_task_files("./output/results/_2019-04-01_17:41:01.781605/2019-04-01/Mi_MIX_3_5G")
    # analysis_crash_and_anr(crash_list, anr_list)
    logger.info('启动服务')
    logger.info('启动定时任务处理器')
    clear_task()  # 清理老的定时任务
    DevicesManagerTask()()  # 读取设备信息入库
    pid = RedisServices().timing_task(timing_tasks_config)  # 启动定时任务处理器
    logger.info('启动定时任务处理器的pid：%s' % pid)
    app = web.application(urls, globals())
    app.run()
    logger.info('关闭服务')


if __name__ == '__main__':
    print sys.argv
    launch()
